import { USER } from '@/services/admin/typings'
import { getUserListByRoleKey } from '@/services/admin/user'
import { CustomerVO, getCustomerList } from '@/services/CustomerService'
import { getGoodsList } from '@/services/GoodsService'
import { OrderVO } from '@/services/OrderService'
import {
  ModalForm,
  ProFormDateTimePicker,
  ProFormDependency,
  ProFormMoney,
  ProFormSelect,
  ProFormText,
  ProFormTextArea,
} from '@ant-design/pro-components'
import { ProFormGroup } from '@ant-design/pro-form'
import { ProFormInstance } from '@ant-design/pro-form/lib'
import { RequestOptionsType } from '@ant-design/pro-utils'
import { useModel } from '@umijs/max'
import { useRequest } from 'ahooks'
import { Spin } from 'antd'
import dayjs from 'dayjs'
import { useRef } from 'react'

export interface OrderUpdateModalProps {
  onFinish: (formData: any) => Promise<boolean | void>
  order?: OrderVO
  open: boolean
  onOpenChange: (state: boolean) => void
  // 场景
  scene: 'customer' | 'order'
}

const optionItem = (item: { label: any; value: any; id: any; name?: string; phone?: string; wxId?: string }) => {
  return (
    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
      <div className="name">{item?.name || '-'}</div>
      <div className="other" style={{ color: '#8c8c8c' }}>
        <div className="phone">{item?.phone || '-'}</div>
        <div className="wx">{item?.wxId || '-'}</div>
      </div>
    </div>
  )
}
const OrderUpdateModal = (props: OrderUpdateModalProps) => {
  const formRef = useRef<ProFormInstance>()

  // 客户搜索State
  let {
    data: customerList,
    run: flushCustomerList,
    loading: searching,
  } = useRequest(getCustomerList, { debounceWait: 300, manual: true })
  let { getDictList } = useModel('dict')
  return (
    <>
      <ModalForm
        key={props.order?.id || props.order?.customerId}
        formRef={formRef}
        title={props.order ? '修改订单' : '添加订单'}
        open={props.open}
        initialValues={props.order}
        onFinish={props.onFinish}
        onOpenChange={props.onOpenChange}
        isKeyPressSubmit
      >
        <ProFormGroup>
          <ProFormText label="id" hidden name="id" />

          <ProFormText label="客户id" hidden name="customerId" />

          <ProFormSelect
            width={400}
            label="客户"
            disabled={props.scene === 'customer'}
            name="customerName"
            rules={[{ required: true, message: '请填写客户姓名' }]}
            fieldProps={{
              showSearch: true,
              filterOption: false,
              notFoundContent: searching ? <Spin size="small" /> : null,
              onSearch: async (keyWord) => {
                if (keyWord) {
                  flushCustomerList({ name: keyWord })
                }
                return []
              },
              optionItemRender: optionItem,
              options: (customerList || []).map((d: CustomerVO) => ({
                label: d.name,
                value: d.id,
                name: d.name,
                phone: d.phone,
                wxId: d.wxId,
              })),
              labelInValue: true,
              onChange: (value) => {
                console.log(value)
                formRef.current?.setFieldsValue({
                  customerId: value.value,
                  customerName: value.label,
                })
              },
            }}
          ></ProFormSelect>

          <ProFormText hidden name="sellerName" />
          <ProFormSelect
            disabled={props.scene === 'customer'}
            width="md"
            label="销售"
            name="sellerId"
            rules={[{ required: true, message: '请选择销售人员' }]}
            request={async () => {
              let userList = await getUserListByRoleKey('seller')
              return userList?.map((user: USER.UserVO) => ({
                label: user.userName,
                value: user.id,
              })) as RequestOptionsType[]
            }}
            fieldProps={{
              labelInValue: true,
              onChange: (value) =>
                formRef.current?.setFieldsValue({
                  sellerName: value.label,
                  sellerId: value.value,
                }),
            }}
          />
          <ProFormText hidden name="goodsName" />
          <ProFormSelect
            width="md"
            label="套系"
            name="goodsId"
            rules={[{ required: true, message: '请选择套系' }]}
            fieldProps={{
              labelInValue: true,
              onChange: (value) => {
                formRef.current?.setFieldsValue({
                  goodsId: value.value,
                  goodsName: value.label,
                  goodsPrice: value.price / 100,
                  realPrice: value.price / 100,
                })
              },
              optionItemRender: (item) => (
                <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                  <span>{item.label}</span>
                  <span>¥{item.price / 100}</span>
                </div>
              ),
            }}
            request={async () => {
              let goodsList = await getGoodsList()
              return goodsList.map((goods) => ({
                label: goods.goodsName,
                value: goods.id,
                price: goods.price,
              }))
            }}
          />

          <ProFormMoney
            label="商品价格"
            disabled
            hidden
            name="goodsPrice"
            rules={[{ required: true, message: '请填写商品价格' }]}
            transform={(value) => ({ goodsPrice: value * 100 })}
          />

          <ProFormMoney
            label="订单价格"
            name="realPrice"
            rules={[{ required: true, message: '请填写订单价格' }]}
            transform={(value) => ({ realPrice: value * 100 })}
          />

          <ProFormMoney
            label="已付金额"
            name="alreadyPay"
            rules={[{ required: true, message: '请填写已付金额' }]}
            transform={(value) => ({ alreadyPay: value * 100 })}
          />

          <ProFormDependency name={['realPrice', 'alreadyPay']}>
            {({ realPrice, alreadyPay }) => (
              <ProFormMoney
                disabled
                name="arrears"
                label="尾款"
                fieldProps={{
                  value: (realPrice - alreadyPay) / 100,
                }}
              />
            )}
          </ProFormDependency>

          <ProFormDateTimePicker
            label="预计拍摄日期"
            name="expectPhotoTime"
            convertValue={(value) => {
              console.log('ccc' + value)
              return value && dayjs(value).format('YYYY-MM-DD HH:mm')
            }}
            transform={(value) => ({ expectPhotoTime: value + ':00' })}
            fieldProps={{
              showTime: { format: 'HH:mm' },
              format: (value) => value.format('YYYY-MM-DD HH:mm'),
              minuteStep: 30,
            }}
          />
          <ProFormSelect
            label="拍摄类型"
            name="photoType"
            rules={[{ required: true, message: '请选择拍摄类型' }]}
            request={async () => getDictList('photo_type') as RequestOptionsType[]}
          />
        </ProFormGroup>
        <ProFormTextArea label="备注" name="remark" />
      </ModalForm>
    </>
  )
}

export default OrderUpdateModal
